﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Utils;
using System.Threading;
using FingerPrintCollection;
using System.IO;
using System.Xml;
using System.Data.SQLite;
using libzkfpcsharp;
using BZ.Logger;
using NDK.Module.BLL;
using NDK.Motion.Sys;
using NDK.Motion.StationLogic;
using BZ.Core.TaskExt;
using NDK.Motion.BLL;

namespace NDK.Frm
{
    public partial class Frm_Login : Form
    {
        public static int Number = 0;
        public static int Number1 = 0;
        private string company = "NDK";

        #region 变量定义
        Thread startCompareFP = null;
        TipForm tipForm;

        bool b_Clicked = false;

        //文件夹加密以及解密
        public string status;
        string[] arr;
        private string _pathkey;

        bool FPLoginSuccess = false;

        string RootFilepath = Application.StartupPath + @"\hdevengine";

        string FilePath = "";
        string FilePath2 = "";

        string blockSN = "";
        string RightblockSN = "";

        public delegate void ShowMessageDelegate(TextBox tb, string msg);
        bool bFingerDeviceInitOk = false;

        UserFPInfoServices userFPInfoServices = new UserFPInfoServices();
        #endregion

        #region 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// <summary>
        /// 窗体对象实例，单例模式,保证整个工程只有一个实例
        /// </summary>
        private static Frm_Login _instance;
        private static readonly object singletonLock = new object();
        public static Frm_Login Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (singletonLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new Frm_Login();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion

        private Frm_Login()
        {
            //Common.username = "superadmin";
            InitializeComponent();
            FilePath = RootFilepath + "\\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";

            FilePath2 = RootFilepath + "\\Procedures";
            arr = new string[6];
            status = "";
            arr[0] = ".{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[1] = ".{21EC2020-3AEA-1069-A2DD-08002B30309D}";
            arr[2] = ".{2559a1f4-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[3] = ".{645FF040-5081-101B-9F08-00AA002F954E}";
            arr[4] = ".{2559a1f1-21d7-11d4-bdaf-00c04f60b9f0}";
            arr[5] = ".{7007ACC7-3202-11D1-AAD2-00805FC1270E}";

            FPFuction.b_startScanFP = false;
            FPFuction.b_recognitioned = false;

            StationManager.MachineProductionMode = RunningModeEnum.ProductionMode;
            ucBtnExt_ProductionMode.FillColor = Color.FromArgb(174, 218, 151);
            ucBtnExt_EmptyMode.FillColor = Color.FromArgb(238, 238, 237);
            ucBtnExt_GRRMode.FillColor = Color.FromArgb(238, 238, 237);

            //ucBtnExt_EmptyMode.Enabled = false;
            //ucBtnExt_GRRMode.Enabled = false;
        }

        private void Frm_Login_Load(object sender, EventArgs e)
        {
            FPFuction.AppendUiLog = LoginLoggerConfiguration.Config();

            #region 页面布局
            int userWidth = Screen.PrimaryScreen.Bounds.Width;
            int userHeight = Screen.PrimaryScreen.Bounds.Height;
            int gap = 15;
            int roundRect_Height = 70;
            Point fr_LoginMode_StartPoint = new Point(gap, gap + roundRect_Height);
            #endregion

            if (Common.isFingerPrintInitialed == false)
            {
                groupPanel4.BackColor = Color.Red;
                buttonX1.Enabled = false;
            }
            else
            {
                groupPanel4.BackColor = Color.White;
                buttonX1.Enabled = true;
            }

            #region 设置登录超时计时器(暂时没用)
#if false       

            //---LogIn Time Out
            //设置时间间隔ms
            int interval = 1000;
            Mytimer = new System.Timers.Timer(interval);
            //设置重复计时
            Mytimer.AutoReset = true;
            //设置执行System.Timers.Timer.Elapsed事件
            Mytimer.Elapsed += new System.Timers.ElapsedEventHandler(Mytimer_tick);
#endif
            #endregion
        }

        private void ShowMessage(TextBox tb, string msg)
        {
            if (tb.InvokeRequired)
            {
                //ShowMessageDelegate myDelegate = ShowMessage; //方法1
                ShowMessageDelegate myDelegate = new ShowMessageDelegate(ShowMessage); //方法2
                tb.Invoke(myDelegate, new object[] { tb, msg });
            }
            else
            {
                tb.Text = msg;// + "\r\n";
            }

        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            FPFuction.AppendUiLog.Log("Start identifying the fingerprint. Press in the fingerprint.......", LogType.Info);

            FPFuction.b_startScanFP = false;
            Common.b_FPLoginClick = true;

            b_Clicked = true;
            startCompareFP = TaskManager.Run(() =>
            {
                StartCompareFP();
            });
            //startCompareFP = new Thread(new ThreadStart(StartCompareFP));
            //startCompareFP.IsBackground = true;
            //startCompareFP.Start();

            tipForm = new TipForm();
            tipForm.Show(this);
        }

        private void Lable_Login_Click(object sender, EventArgs e)
        {
            string UserName = "";

            if (CB_UserName.Text != "")
            {
                switch (CB_UserName.Text)
                {
                    case "Operator":
                        UserName = "Operator";
                        CB_UserName.Text = "";
                        break;

                    case "NDK":
                        UserName = "EN";
                        CB_UserName.Text = "";
                        break;

                    case "Battery QM":
                        UserName = "Battery QM";
                        CB_UserName.Text = "";
                        break;

                    case "Apple":
                        UserName = "Apple";
                        CB_UserName.Text = "";
                        break;

                    default:
                        break;
                }
            }
            else
            {
                MessageBox.Show(this, "请先选择用户名称!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (UserName == "Operator" || UserName == "EN" || UserName == "Battery QM")
            {
                SysUserServices sysUser = new SysUserServices();
                SysUserModel user = sysUser.GetModel(UserName);
                if (user == null)
                {
                    FPFuction.AppendUiLog.Log("UserName:" + (UserName=="EN"? company : UserName )+ ",登陆失败！", LogType.Error);
                    //MessageBox.Show(this, "登陆失败！");
                    return;
                }
                if (user.Password != TextBook_Password.Text)
                {
                    if (user.Username != "Operator")
                    {
                        FPFuction.AppendUiLog.Log("UserName:" + (UserName == "EN" ? company : UserName) + ",登陆失败！", LogType.Error);
                        //MessageBox.Show(this, "登陆失败！");
                        TextBook_Password.Text = "";
                        return;
                    }
                }
                else
                {
                    TextBook_Password.Text = "";
                }

                Common.username = UserName;
                Common.password = user.Password;
                if (Common.username == "superadmin")
                {
                    Common.Authority = "admin";
                }
                else if (Common.username == "Operator")
                {
                    Common.Authority = "OP";
                }
                else if (Common.username == "EN")
                {
                    Common.Authority = "EN";
                }

                FPFuction.AppendUiLog.Log("UserName:" + (UserName == "EN" ? company : UserName) + ",登陆成功！", LogType.Info);
                //MessageBox.Show(this, "登陆成功！");
            }
            else
            {
                FPLoginSuccess = true;
                buttonX1_Click(sender, e);
            }
        }

        private void Label_Quit_Click(object sender, EventArgs e)
        {
            try
            {
                //文件夹加密
                if ((Common.Authority == "Apple" || Common.Authority == "CMT") && Common.isFileSetPassCode == false)
                {
                    Common.isFileSetPassCode = true;
                    //VisionPro.VisionModule.bSetPassCode = true;

                    //记录退出时间
                    string endTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    userFPInfoServices.UpdataFPRecordQuit2Table("FPLoginRecord", Common.Id.ToString(), endTime);
                }
            }
            catch { }

            Common.username = "Operator";
            Common.Authority = "OP";

            FPFuction.AppendUiLog.Log("已退出登录", LogType.Info);

        }

        private void CB_UserName_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (CB_UserName.SelectedIndex)
            {
                case 0:
                    TextBook_Password.Enabled = false;
                    break;
                case 1:
                    TextBook_Password.Enabled = true;
                    break;
                case 2:
                    TextBook_Password.Enabled = false;
                    MessageBox.Show(this, "请直接点击登录按钮，进行指纹验证!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case 3:
                    TextBook_Password.Enabled = false;
                    MessageBox.Show(this, "请直接点击登录按钮，进行指纹验证!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                default:
                    break;
            }
        }

        private void buttonX5_Click(object sender, EventArgs e)
        {
            Dlg_FPLogInRecord FPRecord = new Dlg_FPLogInRecord();
            FPRecord.Show(this);
        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            Dlg_AdminFPRegiste dlg_AdminFPRegiste = new Dlg_AdminFPRegiste();
            dlg_AdminFPRegiste.Show(this);
        }

        private void ucBtnExt_ProductionMode_BtnClick(object sender, EventArgs e)
        {
            if (Common.username == "superadmin"
                   || Common.Authority == "Admin"
                   || Common.Authority == "Apple"
                   || Common.Authority == "CMT"
                   || Common.Authority == "EN"
               )
            {
                if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Running
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Alarm
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Pause
                    )
                {
                    StationManager.MachineProductionMode = RunningModeEnum.ProductionMode;
                    ucBtnExt_ProductionMode.FillColor = Color.FromArgb(174, 218, 151);
                    ucBtnExt_EmptyMode.FillColor = Color.FromArgb(238, 238, 237);
                    ucBtnExt_GRRMode.FillColor = Color.FromArgb(238, 238, 237);

                    ucBtnExt_EmptyMode.Enabled = false;
                    ucBtnExt_GRRMode.Enabled = false;
                    Common.GRR循环模式 = false;
                    Machine.OmronPLC.Write("stPC_PLC.Spare_BOOL[2]", false);
                    FPFuction.AppendUiLog.Log("UserName:" + (Common.username == "EN" ? company : Common.username) + "切换运行模式到ProductionMode！", LogType.Info);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ucBtnExt_EmptyMode_BtnClick(object sender, EventArgs e)
        {
            if ((Common.username == "superadmin"
              || Common.Authority == "Admin"
              || Common.Authority == "Apple"
              || Common.Authority == "CMT"
              || Common.Authority == "EN"))
            {

                if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Running
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Alarm
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Pause
                    )
                {
                    StationManager.MachineProductionMode = RunningModeEnum.EmptyMode;
                    ucBtnExt_ProductionMode.FillColor = Color.FromArgb(238, 238, 237);
                    ucBtnExt_EmptyMode.FillColor = Color.FromArgb(174, 218, 151);
                    ucBtnExt_GRRMode.FillColor = Color.FromArgb(238, 238, 237);

                    ucBtnExt_ProductionMode.Enabled = false;
                    ucBtnExt_GRRMode.Enabled = false;
                    FPFuction.AppendUiLog.Log("UserName:" + (Common.username == "EN" ? company : Common.username) + "切换运行模式到EmptyMode！", LogType.Info);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void ucBtnExt_GRRMode_BtnClick(object sender, EventArgs e)
        {

            if ((Common.username == "superadmin"
                  || Common.Authority == "Admin"
                  || Common.Authority == "Apple"
                  || Common.Authority == "CMT"
                  || Common.Authority == "EN"))
            {
                if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Running
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Alarm
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Pause
                    )
                {
                    Frm_Setting.Instance.cb_ShieldAutoLoad.Checked = true;//手动上料
                    StationManager.MachineProductionMode = RunningModeEnum.GRRMode;
                    ucBtnExt_ProductionMode.FillColor = Color.FromArgb(238, 238, 237);
                    ucBtnExt_EmptyMode.FillColor = Color.FromArgb(238, 238, 237);
                    ucBtnExt_GRRMode.FillColor = Color.FromArgb(174, 218, 151);

                    ucBtnExt_ProductionMode.Enabled = false;
                    ucBtnExt_EmptyMode.Enabled = false;
                    Common.GRR循环模式 = true;
                    Machine.OmronPLC.Write("stPC_PLC.Spare_BOOL[2]", true);
                    FPFuction.AppendUiLog.Log("UserName:" + (Common.username == "EN" ? company : Common.username) + "切换运行模式到GRRMode！", LogType.Info);
                }
            }
            else
            {
                MessageBox.Show(this, "无权限!", "Tip", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 中控智慧指纹锁相关函数
        /// <summary>
        /// 初始化指纹仪
        /// </summary>
        /// <returns>是否初始化成功，true成功，false失败</returns>
        public bool InitFPDevice()
        {
            try
            {
                if (!FPFuction.InitFPDevice())
                {
                    Common.AppendUiLog.Log("Fingerprint initial failed!", LogType.Error);
                    return false;
                }
                else
                {
                    Common.AppendUiLog.Log("Fingerprint initial ok!", LogType.Info);
                }

                if (!FPFuction.OpenFPDevice())
                {
                    Common.AppendUiLog.Log("Fingerprint open failed!", LogType.Error);
                    return false;
                }
                else
                {
                    //Thread captureThread = new Thread(new ThreadStart(DoCapture));
                    //captureThread.IsBackground = true;
                    //captureThread.Start();
                    Thread captureThread = TaskManager.Run(() =>
                    {
                        DoCapture();
                    });

                    FPFuction.bIsTimeToDie = false;
                    Common.AppendUiLog.Log("Fingerprint open successful!", LogType.Info);
                }
            }
            catch (Exception er)
            {
                Common.AppendUiLog.Log("Fingerprint exception！", LogType.Error);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 得到指纹图像后触发的事件函数
        /// </summary>
        private void DoCapture()
        {
            while (!FPFuction.bIsTimeToDie)
            {
                FPFuction.cbCapTmp = 2048;
                int ret = zkfp2.AcquireFingerprint(FPFuction.mDevHandle, FPFuction.FPBuffer, FPFuction.CapTmp, ref FPFuction.cbCapTmp);
                if (ret == zkfp.ZKFP_ERR_OK)
                {
                    try
                    {
                        FPFuction.SendMessage(this.Handle, FPFuction.MESSAGE_CAPTURED_OK, IntPtr.Zero, IntPtr.Zero);
                    }
                    catch (Exception ex)
                    {

                    }
                    finally
                    {
                    }

                }
                Thread.Sleep(200);
            }
        }

        /// <summary>
        /// 重载窗口相应事件
        /// </summary>
        /// <param name="m"></param>
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case FPFuction.MESSAGE_CAPTURED_OK:
                    {
                        FPFuction.b_startScanFP = true;

                        MemoryStream ms = new MemoryStream();
                        BitmapFormat.GetBitmap(FPFuction.FPBuffer, FPFuction.mfpWidth, FPFuction.mfpHeight, ref ms);
                        Bitmap bmp = new Bitmap(ms);
                        this.pictureBox1.Image = bmp;

                        if (FPFuction.IsRegister)  //注册
                        {
                            int ret = zkfp.ZKFP_ERR_OK;
                            int fid = 0, score = 0;
                            ret = zkfp2.DBIdentify(FPFuction.mDBHandle, FPFuction.CapTmp, ref fid, ref score);

                            if (zkfp.ZKFP_ERR_OK == ret)
                            {
                                FPFuction.AppendUiLog.Log("The fingerprint has been registered! fid = " + fid + "!", LogType.Error);
                                FPFuction.IsRegister = false;
                                return;
                            }
                            if (FPFuction.RegisterCount > 0 && zkfp2.DBMatch(FPFuction.mDBHandle, FPFuction.CapTmp, FPFuction.RegTmps[FPFuction.RegisterCount - 1]) <= 0)
                            {
                                MessageBox.Show("Please press the same finger three times to register again！！ ", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                FPFuction.AppendUiLog.Log("Please press the same finger three times to register again", LogType.Error);
                                FPFuction.IsRegister = false;
                                return;
                            }
                            Array.Copy(FPFuction.CapTmp, FPFuction.RegTmps[FPFuction.RegisterCount], FPFuction.cbCapTmp);
                            String strBase64 = zkfp2.BlobToBase64(FPFuction.CapTmp, FPFuction.cbCapTmp);
                            byte[] blob = zkfp2.Base64ToBlob(strBase64);
                            FPFuction.RegisterCount++;
                            if (FPFuction.RegisterCount >= FPFuction.REGISTER_FINGER_COUNT)
                            {
                                FPFuction.RegisterCount = 0;

                                if (zkfp.ZKFP_ERR_OK == (ret = zkfp2.DBMerge(FPFuction.mDBHandle, FPFuction.RegTmps[0], FPFuction.RegTmps[1], FPFuction.RegTmps[2], FPFuction.RegTmp, ref FPFuction.cbRegTmp)) &&
                                       zkfp.ZKFP_ERR_OK == (ret = zkfp2.DBAdd(FPFuction.mDBHandle, FPFuction.iFid, FPFuction.RegTmp)))
                                {
                                    FPFuction.iFid++;

                                    int i = 2047;
                                    for (; i >= 0; i--)
                                    {
                                        if (FPFuction.RegTmp[i] != 0)
                                            break;
                                    }
                                    int length = i + 1;
                                    String strRegTmp = zkfp2.BlobToBase64(FPFuction.RegTmp, length);
                                    FPFuction.FPInfo.UserFPFeatureData = strRegTmp;
                                    userFPInfoServices.InsertFPInfo2Table("UserFPInfo", FPFuction.FPInfo.UserName, FPFuction.FPInfo.UserAuthority, FPFuction.FPInfo.UserFPFeatureData);
                                    MessageBox.Show("Fingerprint entry completed!", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    FPFuction.AppendUiLog.Log("Fingerprint registration successful!", LogType.Info);
                                }
                                else
                                {
                                    MessageBox.Show("Fingerprint entry failed! error code = " + ret.ToString(), "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    FPFuction.AppendUiLog.Log("Fingerprint registration failed! error code = " + ret.ToString(), LogType.Error);
                                }
                                FPFuction.IsRegister = false;
                                return;
                            }
                            else
                            {
                                FPFuction.AppendUiLog.Log("You need to press " + (FPFuction.REGISTER_FINGER_COUNT - FPFuction.RegisterCount) + " times more", LogType.Alert);
                            }
                        }
                        else
                        {
                            if (FPFuction.bIdentify)  //1:N识别 (暂时没用)
                            {
#if false
                                int ret = zkfp.ZKFP_ERR_OK;
                                int fid = 0, score = 0;
                                ret = zkfp2.DBIdentify(FPFuction.mDBHandle, FPFuction.CapTmp, ref fid, ref score);
                                if (zkfp.ZKFP_ERR_OK == ret)
                                {
                                    FPFuction.AppendUiLog.Log("识别指纹成功，fid= " + fid + ", score = " + score + "!", Color.Green);
                                    return;
                                }
                                else
                                {
                                    FPFuction.AppendUiLog.Log("识别指纹失败 , ret = " + ret.ToString(), Color.Red);
                                    return;
                                }
#endif
                            }
                            else  //1:1识别
                            {
                                //捞取数据库中的指纹信息
                                DataSet dataSet = userFPInfoServices.SelectTotalInfo("UserFPInfo");

                                //while (true)
                                //{
                                //    Thread.Sleep(5);
                                //}

                                if (dataSet.Tables[0].Rows.Count > 0)
                                {
                                    for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                                    {
                                        string FPFeatureData = dataSet.Tables[0].Rows[i]["UserFPFeatureData"].ToString();
                                        byte[] blob = new byte[2048];
                                        //blob = zkfp2.Base64ToBlob(FPFeatureData);
                                        if (FPFeatureData.Length < 16)
                                        {
                                            continue;
                                        }
                                        blob = Convert.FromBase64String(FPFeatureData);

                                        int r = zkfp2.DBMatch(FPFuction.mDBHandle, FPFuction.CapTmp, blob);
                                        if (r > 50)
                                        {
                                            FPFuction.FPInfo.UserName = dataSet.Tables[0].Rows[i]["UserName"].ToString();
                                            FPFuction.FPInfo.UserAuthority = dataSet.Tables[0].Rows[i]["UserAuthority"].ToString();

                                            Common.Authority = FPFuction.FPInfo.UserAuthority;

                                            ShowMessage(userNameTxt, FPFuction.FPInfo.UserName);
                                            ShowMessage(authorityTxt, FPFuction.FPInfo.UserAuthority);

                                            Common.fingerPrintAuthority = FPFuction.FPInfo.UserAuthority;
                                            Common.fingerPrintUserName = FPFuction.FPInfo.UserName;
                                            FPFuction.AppendUiLog.Log("匹配成功! Score：" + r.ToString(), LogType.Info);


                                            if (Common.Authority == "Apple" || Common.Authority == "CMT")// || Common.Authority == "CMT"
                                            {
                                                FPLoginSuccess = true;

                                                try
                                                {
                                                    ReleasePassCode();
                                                }
                                                catch (Exception)
                                                {
                                                }

                                                //添加登录记录
                                                try
                                                {
                                                    string FP_Owner = Common.fingerPrintUserName;
                                                    string FP_Authority = Common.fingerPrintAuthority;
                                                    DataSet dataSet_FP_Record = userFPInfoServices.SelectTotalInfo("FPLoginRecord");
                                                    Common.Id = dataSet_FP_Record.Tables[0].Rows.Count + 1;

                                                    string LoginStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    userFPInfoServices.InsertFPRecord2Table("FPLoginRecord", Common.Id.ToString(), FP_Owner, FP_Authority, LoginStartTime);

                                                }
                                                catch (Exception ex)
                                                {

                                                }
                                                Common.isFileSetPassCode = false;

                                                string halconExamples = FileUtils.GetAppDirectory();


                                                //Common.HalconvisionInitil = HalconVisionOperate.IntilCamerafile();//这句话会导致无法访问算法平台找线工具

                                                Common.ProcedurePath = halconExamples + @"\hdevengine\procedures";
                                                if (Common.Authority == "Apple")
                                                {
                                                    Common.username = "superadmin";

                                                    SQLiteConnection conn = SQLiteUtils.GetConnection(Common.DatabaseName);
                                                    SysUserServices sysUser = new SysUserServices();
                                                    sysUser.CreateUserTable("User", conn);
                                                    SysUserModel user = sysUser.GetModel(Common.username);

                                                    Common.password = user.Password;

                                                    Common.FPForm.ShowDialog(this);

                                                }

                                                if (FPLoginSuccess == true)
                                                {
                                                    FPLoginSuccess = false;
                                                    MessageBox.Show(this, "登陆成功!");
                                                }

                                            }
                                            break;
                                        }
                                        else
                                        {
                                            if (i == dataSet.Tables[0].Rows.Count - 1)  //最后一个也没有匹配到，证明没有录入指纹，非法权限
                                            {
                                                //再在Admin的数据库中匹配指纹
                                                DataSet dataSetAdmin = userFPInfoServices.SelectTotalInfo("AdminFPInfo");
                                                if (dataSetAdmin.Tables[0].Rows.Count > 0)
                                                {
                                                    for (int j = 0; j < dataSetAdmin.Tables[0].Rows.Count; j++)
                                                    {
                                                        FPFeatureData = dataSetAdmin.Tables[0].Rows[j]["UserFPFeatureData"].ToString();

                                                        r = zkfp2.DBMatch(FPFuction.mDBHandle, FPFuction.CapTmp, blob);


                                                        if (r > 50)
                                                        {
                                                            FPFuction.FPInfo.UserName = dataSetAdmin.Tables[0].Rows[j]["UserName"].ToString();
                                                            FPFuction.FPInfo.UserAuthority = "Admin";

                                                            Common.Authority = FPFuction.FPInfo.UserAuthority;
                                                            Common.fingerPrintAuthority = FPFuction.FPInfo.UserAuthority;
                                                            Common.fingerPrintUserName = FPFuction.FPInfo.UserName;

                                                            try
                                                            {
                                                                ReleasePassCode();
                                                            }
                                                            catch (Exception)
                                                            {
                                                            }

                                                            Common.isFileSetPassCode = false;
                                                            string halconExamples = FileUtils.GetAppDirectory();


                                                            Common.ProcedurePath = halconExamples + @"\hdevengine\procedures";

                                                            if (Common.Authority == "Admin")
                                                            {
                                                                Common.username = "superadmin";

                                                                SQLiteConnection conn = SQLiteUtils.GetConnection(Common.DatabaseName);
                                                                SysUserServices sysUser = new SysUserServices();
                                                                sysUser.CreateUserTable("User", conn);
                                                                SysUserModel user = sysUser.GetModel(Common.username);

                                                                Common.password = user.Password;


                                                                Common.FPForm.ShowDialog(this);
                                                            }

                                                            break;
                                                        }
                                                        else
                                                        {
                                                            if (j == dataSetAdmin.Tables[0].Rows.Count - 1)  //最后一个也没有匹配到，证明没有录入指纹，非法权限
                                                            {
                                                                FPFuction.AppendUiLog.Log("无任何权限指纹!!", LogType.Error);
                                                                Common.Authority = "";

                                                                MessageBox.Show(this, "无任何权限指纹!", "识别结果", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                                                            }
                                                        }

                                                    }
                                                }
                                                else
                                                {
                                                    MessageBox.Show(this, "该用户不存在指纹信息!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                }
                                            }
                                        }
                                    }

                                    FPFuction.bIdentify = true;
                                }
                                else
                                {
                                    //MessageBox.Show("读取部门数据失败!", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    FPFuction.AppendUiLog.Log("Failed to read department data!", LogType.Error);
                                }
                            }
                        }
                    }
                    break;

                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }

        /// <summary>
        /// 指纹比对函数
        /// </summary>
        private void StartCompareFP()
        {
            //文本框清除
            ShowMessage(userNameTxt, "");
            ShowMessage(authorityTxt, "");

            if (FPFuction.bIdentify)  //要用1:1识别方法
            {
                FPFuction.bIdentify = false;
                FPFuction.AppendUiLog.Log("Start identifying the fingerprint. Press in the fingerprint.......", LogType.Info);
            }
        }
        #endregion

        #region 文件夹加密/解密相关函数
        public string pathkey
        {
            get
            {
                return _pathkey;
            }
            set
            {
                _pathkey = value;
            }
        }

        private string getstatus(string stat)
        {
            for (int i = 0; i < 6; i++)
                if (stat.LastIndexOf(arr[i]) != -1)
                    stat = stat.Substring(stat.LastIndexOf("."));
            return stat;
        }

        private bool checkpassword()
        {
            XmlTextReader read;
            if (pathkey == null)
                read = new XmlTextReader(RootFilepath + "\\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}" + "\\p.xml");
            else
                read = new XmlTextReader(RootFilepath + "\\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}" + "\\p.xml");
            if (read.ReadState == ReadState.Error)
                return true;
            else
            {
                try
                {
                    while (read.Read())
                        if (read.NodeType == XmlNodeType.Text)
                        {
                            if (read.Value == "1234")
                            {
                                read.Close();
                                return true;
                            }
                            else
                            {
                                read.Close();
                                return false;
                            }
                        }
                }
                catch { return true; }

            }
            read.Close();
            return false;
        }

        private Boolean setpassword(string path)
        {
            //frmPassword p = new frmPassword();

            XmlDocument xmldoc = new XmlDocument();
            XmlElement xmlelem;
            XmlNode xmlnode;
            XmlText xmltext;
            xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            xmldoc.AppendChild(xmlnode);
            xmlelem = xmldoc.CreateElement("", "ROOT", "");
            xmltext = xmldoc.CreateTextNode("1234");
            xmlelem.AppendChild(xmltext);
            xmldoc.AppendChild(xmlelem);
            xmldoc.Save(path + "\\p.xml");

            //p.path = path;
            //p.ShowDialog();
            return true;
        }

        public void SetPassCode()  //设置文件夹加密
        {
            try
            {
                //算法文件加密
                DirectoryInfo d = new DirectoryInfo(FilePath2);
                status = arr[0];
                setpassword(@"");
                if (!d.Root.Equals(d.Parent.FullName))
                {
                    d.MoveTo(d.Parent.FullName + "\\" + d.Name + status);//文件夹重命名
                }
                else
                    d.MoveTo(d.Parent.FullName + d.Name + status);

            }
            catch (Exception ex)
            {
            }

        }

        public void ReleasePassCode() //设置文件夹解密
        {
            status = arr[0];

            DirectoryInfo d = new DirectoryInfo(FilePath);

            status = getstatus(status);
            bool s = checkpassword();
            if (s)
            {
                File.Delete(RootFilepath + "\\Procedures.{2559a1f2-21d7-11d4-bdaf-00c04f60b9f0}" + "\\key.xml");
                string path = FilePath.Substring(0, FilePath.LastIndexOf("."));
                d.MoveTo(path);
            }
        }
        #endregion

        private void Frm_Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.Escape)
            {

            }
        }


        private void buttonX2_Click(object sender, EventArgs e)
        {
            Common.FPForm.ShowDialog(this);
        }

        private void TextBook_Password_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Lable_Login_Click(sender, e);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if ((Common.username == "superadmin"
                || Common.Authority == "Admin"
                || Common.Authority == "Apple"
                || Common.Authority == "CMT"
                || Common.Authority == "EN"))
            {
                if (MachineStatusManager.CurrentMachineStatus != MachineStatus.Running
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Homing
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Alarm
                    || MachineStatusManager.CurrentMachineStatus != MachineStatus.Pause
                    )
                {
                    ucBtnExt_ProductionMode.Enabled = true;
                    ucBtnExt_GRRMode.Enabled = true;
                    ucBtnExt_EmptyMode.Enabled = true;
                }
            }
          
        }
    }
}
